//
//  Tool.m
//  TransportationSecretary
//
//  Created by lpc on 13-7-4.
//  Copyright (c) 2013年 mac. All rights reserved.
//
#import "LPCAppHeader.h"
#import "LPCTool.h"
#import "Reachability.h"
#import <SystemConfiguration/CaptiveNetwork.h>
#import <CommonCrypto/CommonDigest.h>
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>

@implementation LPCTool
+ (NSString *)getUserAgent
{
    return [NSString stringWithFormat:@"iOS/%@/%@/%@/%@", [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey], [UIDevice currentDevice].systemName, [UIDevice currentDevice].systemVersion, [UIDevice currentDevice].model];
}

+ (UIColor *)getBackgroundColor
{
    return [UIColor colorWithRed:235.0 / 255 green:235.0 / 255 blue:243.0 / 255 alpha:1.0];
}

+ (UIColor *)getCellBackgroundColor
{
    return [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:1.0];
}

+ (NSString *)getChatDateTimeString:(long long)time
{
    NSDate *curDate = [NSDate date];
    NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:time / 1000];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];

    NSString *result1 = [formatter stringFromDate:curDate];
    NSString *result2 = [formatter stringFromDate:date];
    if ([result1 isEqualToString:result2])
    {
        [formatter setDateFormat:@"HH:mm"];
        result2 = [formatter stringFromDate:date];
        return result2;
    }
    else
    {
        return result2;
    }
}

+ (NSString *)getUrlDateTimeString:(NSString *)timeStr
{
    NSString *result = @"";
    if (timeStr != [NSNull null])
    {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSDate *date = [formatter dateFromString:timeStr];
        NSDate *curDate = [NSDate date];
        NSTimeInterval timeInterval = [curDate timeIntervalSinceDate:date];
        int dayNum = timeInterval / (24 * 3600);
        if (dayNum <= 0)
        {
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"yyyy-MM-dd"];

            NSString *result1 = [formatter stringFromDate:curDate];
            NSString *result2 = [formatter stringFromDate:date];
            if ([result1 isEqualToString:result2])
            {
                [formatter setDateFormat:@"HH:mm"];
                result2 = [formatter stringFromDate:date];
                result = @"今天";
            }
            else
            {
                result = @"昨天";
            }
        }
        else
        {
            result = [NSString stringWithFormat:@"%d天前", dayNum];
        }
    }
    return result;
}

+ (NSString *)getCurDateTimeString:(NSDateFormatter *)formatter
{
    NSDate *curDate = [NSDate date];
    return [self getDateTimeString:curDate formatter:formatter];
}

+ (NSString *)getCurDateString
{
    NSDate *curDate = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    return [self getDateTimeString:curDate formatter:formatter];
}

+ (NSString *)getDateTimeString:(NSDate *)date formatter:(NSDateFormatter *)formatter
{
    return [formatter stringFromDate:date];
}

+ (int)getCurYear
{
    NSDate *curDate = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy"];
    NSString *result = [formatter stringFromDate:curDate];
    return [result intValue];
}

+ (int)getCurMonth
{
    NSDate *curDate = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM"];
    NSString *result = [formatter stringFromDate:curDate];
    return [result intValue];
}

+ (NSString *)getCurMonDayString
{
    NSDate *curDate = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM-dd"];
    return [formatter stringFromDate:curDate];
}

+ (NSString *)getDateString:(long long)time
{
    NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:time / 1000];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *result = [formatter stringFromDate:date];
    return result;
}

+ (NSString *)getTimeString:(long long)time
{
    NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:time / 1000];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"HH:mm"];
    NSString *result = [formatter stringFromDate:date];
    return result;
}

+ (NSString *)getDateTimeSecString:(long long)time
{
    NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:time / 1000];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *result = [formatter stringFromDate:date];
    return result;
}

+ (NSString *)getDateTimeString:(long long)time
{
    NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:time / 1000];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    NSString *result = [formatter stringFromDate:date];
    return result;
}

+ (long long)getTimeLongLong:(NSString *)timeStr
{
    long long result = 0;
    if (timeStr != [NSNull null] && timeStr.length > 10)
    {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSDate *date = [formatter dateFromString:timeStr];
        result = date.timeIntervalSince1970;
    }
    return result;
}

+ (NSString *)weekdayStringFromDate:(NSDate *)inputDate
{
    NSArray *weekdays = [NSArray arrayWithObjects:[NSNull null], @"星期天", @"星期一", @"星期二", @"星期三", @"星期四", @"星期五", @"星期六", nil];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    [calendar setTimeZone:timeZone];
    NSCalendarUnit calendarUnit = NSCalendarUnitWeekday;
    NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];
    return [weekdays objectAtIndex:theComponents.weekday];
}

+ (BOOL)isDigitString:(NSString *)str
{
    BOOL isDigit = NO;
    NSCharacterSet *digitCharSet = [NSCharacterSet decimalDigitCharacterSet];
    NSCharacterSet *strCharSet = [NSCharacterSet characterSetWithCharactersInString:str];

    if ([digitCharSet isSupersetOfSet:strCharSet])
    {
        isDigit = YES;
    }
    else
    {
        isDigit = NO;
    }
    return isDigit;
}

+ (BOOL)isDigitCharacterString:(NSString *)str
{
    BOOL isDigitCharacter = NO;
    NSString *regex = @"[0-9a-zA-Z]+";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isMatch = [pred evaluateWithObject:str];
    if (isMatch)
    {
        return isDigitCharacter = YES;
    }
    else
    {
        return isDigitCharacter = NO;
    }
    return isDigitCharacter;
}

#pragma mark - 颜色转换 IOS中十六进制的颜色转换为UIColor
+ (UIColor *)colorWithHexString:(NSString *)color
{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];

    // String should be 6 or 8 characters
    if ([cString length] < 6)
    {
        return [UIColor clearColor];
    }

    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];

    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;

    // r
    NSString *rString = [cString substringWithRange:range];

    // g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];

    // b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];

    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];

    return [UIColor colorWithRed:((float)r / 255.0f)green:((float)g / 255.0f)blue:((float)b / 255.0f)alpha:1.0f];
}

+ (BOOL)isNetworkRunning
{
    return [LPCTool IsEnable3G] || [LPCTool IsEnableWIFI];
}

// 是否wifi
+ (BOOL)IsEnableWIFI
{
    return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);
}

// 是否3G
+ (BOOL)IsEnable3G
{
    return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable);
}

+ (NSString *)fetchSSIDInfo
{
    NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
    NSLog(@"Supported interfaces: %@", ifs);
    id info = nil;
    for (NSString *ifnam in ifs)
    {
        info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
        NSLog(@"%@ => %@", ifnam, info);
        if (info && [(NSArray *)info count])
        {
            break;
        }
    }
    NSString *ssid = nil;
    if (info != nil)
    {
        ssid = [info objectForKey:@"SSID"];
        if (ssid != nil && [ssid characterAtIndex:0] == '"')
        {
            ssid = [ssid substringFromIndex:1];
        }
        if (ssid != nil && [ssid characterAtIndex:(ssid.length - 1)] == '"')
        {
            ssid = [ssid substringToIndex:(ssid.length - 2)];
        }
    }

    return ssid;
}

+ (long long)getMessageId
{
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMddHHmmssSSS"];
    NSString *result = [formatter stringFromDate:date];
    return [result longLongValue];
}

+ (long long)ntohll:(long long)llValue
{
    struct STRUCT
    {
        int val1;
        int val2;
    };
    union UNION_CHANGE
    {
        long long int llValue;
        struct STRUCT stValue;
    };
    union UNION_CHANGE u1, u2;
    u1.llValue = llValue;
    u2.stValue.val1 = ntohl(u1.stValue.val2);
    u2.stValue.val2 = ntohl(u1.stValue.val1);
    return u2.llValue;
}

+ (UIImage *)OriginImage:(UIImage *)image scaleToSize:(CGSize)size
{
    UIGraphicsBeginImageContext(size); // size 为CGSize类型，即你所需要的图片尺寸

    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];

    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    return scaledImage; //返回的就是已经改变的图片
}

+ (void)shakeAndPlaySound:(BOOL)isNoSound:(BOOL)isShake
{
    if (isShake)
    {
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    }
    if (!isNoSound)
    {
        //        static SystemSoundID soundID = 0;
        //        NSString * path = [[NSBundle mainBundle] pathForResource:@"24" ofType:@"wav"];
        //        if (path) {
        //            AudioServicesCreateSystemSoundID( (CFURLRef)CFBridgingRetain([NSURL fileURLWithPath:path]), &soundID );
        //        }
        ////        AudioServicesPlaySystemSound( 1109);
        //         AudioServicesPlaySystemSound( soundID);
        //        NSString *path;
        //
        //        NSURL *url;
        //
        //        //where you are about to add sound
        //
        //        path =[[NSBundle mainBundle] pathForResource:@"sound" ofType:@"wav"];
        //        url = [NSURL fileURLWithPath:path];
        //        AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
        //        [player setVolume:1.0];
        //        [player play];
        [LPCTool initSound];
    }
}

+ (UIImage *)scale:(UIImage *)sourceImg toSize:(CGSize)size
{
    UIGraphicsBeginImageContext(size);
    [sourceImg drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}
+ (CGSize)scaleSize:(CGSize)sourceSize
{
    float width = sourceSize.width;
    float height = sourceSize.height;
    if (width >= height)
    {
        return CGSizeMake(800, 800 * height / width);
    }
    else
    {
        return CGSizeMake(800 * width / height, 800);
    }
}

+ (void)putImage:(NSData *)imageData withName:(NSString *)path
{
    if (imageData == nil)
    {
        return;
    }
    [imageData writeToFile:path atomically:YES];
}

+ (NSString *)getFilePathName:(NSString *)imageName
{
    NSString *tmpPath = [NSHomeDirectory() stringByAppendingPathComponent:@"tmp"];
    NSString *path = [tmpPath stringByAppendingPathComponent:imageName];
    return path;
}

+ (NSString *)getTradeNo:(NSString *)result
{
    NSArray *params = [result componentsSeparatedByString:@"&"];
    for (NSString *param in params)
    {
        NSRange range = [param rangeOfString:@"out_trade_no"];
        if (range.location != NSNotFound)
        {
            NSArray *results = [param componentsSeparatedByString:@"\""];
            return results[1];
        }
    }
    return nil;
}

+ (void)initSound
{
    static AVAudioPlayer *player = nil;
    if (player == nil)
    {
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];

        NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"sound" ofType:@"mp3"];
        NSURL *soundUrl = [[NSURL alloc] initFileURLWithPath:soundPath];
        player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundUrl error:nil];
        player.numberOfLoops = 1;
        [player prepareToPlay];
    }
    [player play];
}

+ (UIImage *)imageWithColor:(UIColor *)color andSize:(CGSize)size
{
    CGRect rect = CGRectMake(0.0f, 0.0f, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

+ (NSString *)filterHTML:(NSString *)html
{
    NSScanner *scanner = [NSScanner scannerWithString:html];
    NSString *text = nil;
    while ([scanner isAtEnd] == NO)
    {
        //找到标签的起始位置
        [scanner scanUpToString:@"<" intoString:nil];
        //找到标签的结束位置
        [scanner scanUpToString:@">" intoString:&text];
        //替换字符
        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>", text] withString:@""];
    }
    //    NSString * regEx = @"<([^>]*)>";
    //    html = [html stringByReplacingOccurrencesOfString:regEx withString:@""];
    html = [html stringByReplacingOccurrencesOfString:@"&nbsp;" withString:@" "];
    return html;
}

+ (NSString *)getOSVersion
{
    return [NSString stringWithFormat:@"LPC iOS/%@/%@/%@/%@", AppVersion, [UIDevice currentDevice].systemName, [UIDevice currentDevice].systemVersion, [UIDevice currentDevice].model];
}

+ (NSString *)getFormattedString:(float)value decimalNum:(int)decimalNum default:(NSString *)defaultStr
{
    if (value == 0)
    {
        return defaultStr;
    }
    else if (decimalNum == 0)
    {
        return [NSString stringWithFormat:FORMAT_DECIMAL_0, value];
    }
    else if (decimalNum == 1)
    {
        return [NSString stringWithFormat:FORMAT_DECIMAL_1, value];
    }
    else
    {
        return [NSString stringWithFormat:FORMAT_DECIMAL_2, value];
    }
}

+ (NSString *)getFormattedPercentString:(float)value decimalNum:(int)decimalNum default:(NSString *)defaultStr
{
    NSString *result;
    if (value == 0)
    {
        result = defaultStr;
    }
    else if (decimalNum == 0)
    {
        result = [NSString stringWithFormat:FORMAT_DECIMAL_0_PERCENT, value];
    }
    else if (decimalNum == 1)
    {
        result = [NSString stringWithFormat:FORMAT_DECIMAL_1_PERCENT, value];
    }
    else
    {
        result = [NSString stringWithFormat:FORMAT_DECIMAL_2_PERCENT, value];
    }
    if (value > 0)
    {
        result = [NSString stringWithFormat:@"+%@", result];
    }
    return result;
}

@end
